﻿

public class NetHandler_Apply : GameServerMessageHandler
{
    public const string Key = "Apply";

    public static NetHandler_Apply NewHandler()
    {
        return new NetHandler_Apply();
    }

    protected override ISerialize NewData() => new ApplyRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        ApplyRequestData requestData = _data as ApplyRequestData;

        GameDebug.Log($"用户{client.userID} 申请认识:{requestData?.targetUserId}");

        UserServer user = Game.instance.GetUser(client.userID);

        ApplyResponseData response = new ApplyResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if (requestData != null)
            {
                bool free = user.data.freeApplyCount > 0;
                if (!free)
                {
                    if(user.data.diamond >= AppConstantData.applyPrice)
                    {
                        user.MniusDiamond(AppConstantData.applyPrice);
                        response.code = 0;
                    }
                    else
                    {
                        response.code = ErrorCode.diamondNotEnough;
                    }
                }
                else
                {
                    user.UpdateFreeApplyCount(user,user.data.freeApplyCount - 1);
                    response.code = 0;
                }

                Apply apply = user.data.AddApply(user.data.id, requestData.targetUserId, Apply.Applying,
                    requestData.message,"", (long)CommonFunctions.GetTimeStampSeconds(),0,0);

                response.apply = apply;

                int ret = applys.SetApply(user.data.id,/* apply.applyId,*/ apply.targetUserId, apply.result,
                    apply.msg, apply.rejectMsg, apply.applyTime, apply.viewTime, apply.resultTime);

                if (ret >= 0)
                    response.code = 0;
                else
                    response.code = -1;
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data != null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
